import Vue from 'vue'
import Vuex from 'vuex'
import router, { constantRoutes, resetRouter } from '@/router'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    routes: sessionStorage.getItem('routes') ? JSON.parse(sessionStorage.getItem('routes')) : [...constantRoutes],
    Permissions: ['add', 'title'] // 获取到的按钮权限标识
    // routes: [...constantRoutes, ...asyncRoutes]
  },
  getters: {
  },
  mutations: {
    setRoutes (state, data) {
      state.routes = data
      sessionStorage.setItem('routes', JSON.stringify(data))
    },
    login (state, points) {
      state.Permissions = points
    },
    logout (state) {
      state.routes = [...constantRoutes]
      resetRouter()
      state.Permissions = []
    }
  },
  actions: {
    // 用户的动态路由
    filterRoutes (ctx, menus) {
      const userlist = []
      constantRoutes.forEach(item => {
        console.log(item, 'item')
        const { permission } = item?.meta
        if (permission && menus?.includes(permission)) {
          // console.log(item)
          if (item.children && item.children.length > 0) {
            const temp = item.children.filter(o => menus.includes(o.meta.permission))
            console.log(temp, 'temp')
            item.children = temp
          }
          userlist.push(item)
        }
      }
      )
      console.log(userlist, 'userlist')
      // userlist.push({ path: '*', redirect: '/404', hidden: true })
      ctx.commit('setRoutes', userlist)

      router.addRoutes(userlist)
    }
  },
  modules: {
  }
})
